package breeze.lepei.der.main_view.presenter;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import breeze.lepei.der.BaseView;
import breeze.lepei.der.R;
import breeze.lepei.der.lepei.LepeiApiUti;
import breeze.lepei.der.main_view.view.IMainView;
import breeze.lepei.der.main_view.view.MainView;
import breeze.lepei.der.usersettings.UserSettings;
import breeze.lepei.der.utils.Alipay;
import breeze.lepei.der.utils.AppTools;
import breeze.lepei.der.utils.MDialog;
import breeze.lepei.der.utils.MLog;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import android.graphics.Bitmap;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import com.google.gson.Gson;
import breeze.lepei.der.main_view.model.LastedExamModel;
import breeze.lepei.der.main_view.model.StuHistoryExamModel;

public class MainPresenter implements IMainPresenter,OnClickListener {

	/**
	*@author BREEZE
	*@description 获取学生考试历史
	*/
	@Override
	public void getStudentHisExam() {
		final UserSettings sets=UserSettings.getInstance(mContext);
		BaseView.getExec().execute(new Runnable(){public void run(){
					try {
						String result=AppTools.getWebContent(LepeiApiUti.getStuHistoryExam(sets.getUserPhone(), sets.getToken(), sets.getStudentId()));
						Gson gson=new Gson();
						StuHistoryExamModel model=gson.fromJson(result,StuHistoryExamModel.class);
						MLog.log(TAG,"考试历史：",result);
						if("200".equals(model.getCode())){
							//TODO：解析
							view.setRecyclerData(model.getObj());
						}else{
							view.showDialog("获取考试历史失败",model.getMsg());
						}
					} catch (IOException e) {
						MLog.logE(TAG,e);
						view.showAppBug(e);
					}
				}});
	}

	/**
	*@author BREEZE
	*@description 获取最新考试成绩
	*/
	@Override
	public void getStudentLastedExam() {
		BaseView.getExec().execute(new Runnable(){public void run(){
					try {
						UserSettings sets=UserSettings.getInstance(mContext);
						String result=AppTools.getWebContent(LepeiApiUti.getLastedExamInfo(sets.getUserPhone(),sets.getToken(),sets.getStudentId()));
						MLog.log(TAG,"成绩数据：",result);
						if(!"".equals(result)){
							Gson gson=new Gson();
							LastedExamModel lastedExam=gson.fromJson(result,LastedExamModel.class);
							view.setLastedExam(lastedExam);
						}
					} catch (IOException e) {
						MLog.logE(TAG,e);
						view.showAppBug(e);
					}
				}});
	}
	
	/**
	*@author BREEZE
	*@description 获取通知
	*@param 文本布局
	*/
	@Override
	public void getNotice(final TextView tv) {
		BaseView.getExec().execute(new Runnable(){
			public void run(){
				try{
					String result=AppTools.getWebContent(LepeiApiUti.getNotice());
					JSONObject obj=new JSONObject(result);
					String code=obj.getString("code");
					if("200".equals(code)){
						JSONObject obj2=obj.getJSONObject("obj");
						final String notice=obj2.getString("notice");
						UserSettings sets=UserSettings.getInstance(mContext);
						sets.setNotice(notice);
						tv.post(new Runnable(){
								public void run(){
									tv.setText(notice);
								}
							});
					}
				}catch(Exception e){
					tv.post(new Runnable(){
						public void run(){
							tv.setText("获取通知失败！");
						}
					});
					view.showAppBug(e);
				}
			}
		});
	}

	/**
	*@author BREEZE
	*@description 获取头像
	*@param 视图/QQ
	*/
	@Override
	public void getHeadImg(final ImageView img, String qq) {
		final String url = "http://q1.qlogo.cn/g?b=qq&nk=" + qq + "&s=640";
		BaseView.getExec().execute(new Runnable(){
				public void run() {
					try {
						Bitmap p1=AppTools.getWebBitmap(url);
						final RoundedBitmapDrawable rbd=RoundedBitmapDrawableFactory.create(mContext.getResources(),p1);
						rbd.setAntiAlias(true);
						rbd.setCircular(true);
						img.post(new Runnable(){public void run(){
									img.setImageDrawable(rbd);
								}});
					} catch (IOException e) {
						MLog.logE(TAG,e);
						img.post(new Runnable(){public void run(){
							img.setImageResource(R.drawable.ic_no_headimg);
						}});
					}
				}
			});
	}

	/**
	*@author BREEZE
	*@description 获取头像
	*@param 上下文
	*/
	@Override
	public void getQQDialog(final ImageView img,final Context context) {
		View head_view=LayoutInflater.from(context).inflate(R.layout.dialog_user_headimg,null);
		Button bta=head_view.findViewById(R.id.headimg_ok);
		TextView cancel=head_view.findViewById(R.id.headimg_cancel);
		final EditText qq_edi=head_view.findViewById(R.id.headimg_edittext);
		final AlertDialog alert=new AlertDialog.Builder(context).create();
		alert.setView(head_view);
		alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		alert.show();
		bta.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				String qq=qq_edi.getText().toString();
				if("".equals(qq)){
					qq_edi.setError("请输入QQ号");
				}else if(qq.length()<6){
					qq_edi.setError("请输入正确的QQ号");
				}else{
					UserSettings sets=UserSettings.getInstance(context);
					sets.setQQ(qq);
					getHeadImg(img,qq);
					alert.dismiss();
				}
			}
		});
		cancel.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				alert.dismiss();
			}
		});
	}

	/**
	*@author BREEZE
	*@description 登录
	*@param 手机号/密码
	*/
	@Override
	public void login(final String phone, final String pass) {
		final String link=LepeiApiUti.login(phone,pass);
		Observable<String> obs=Observable.create(new ObservableOnSubscribe<String>(){
				@Override
				public void subscribe(final ObservableEmitter<String> p1) throws Exception {
					BaseView.getExec().execute(new Runnable(){public void run(){
								try {
									String json=AppTools.getWebContent(link);
									p1.onNext(json);
								} catch (IOException e) {
									p1.onError(e);
									MLog.logE("LoginPresenter",e);
								}
							}});
				}
			});
		Observer<String> server=new Observer<String>(){

			@Override
			public void onComplete() {
			}

			@Override
			public void onError(Throwable p1) {
				view.showDialog("登录失败",p1.toString());
			}

			@Override
			public void onNext(String p1) {
				MLog.log("登录结果",p1);
				try {
					JSONObject obj=new JSONObject(p1);
					int code=obj.getInt("code");
					String msg=obj.getString("msg");
					if(code!=200){
						view.showDialog("提示",msg);
					}else{
						//TODO：登录成功保存数据
						JSONObject obj2=obj.getJSONObject("obj");
						String token=obj2.getString("token");
						String vi=obj2.getString("vi");
						UserSettings usersettings=UserSettings.getInstance(mContext);
						usersettings.setUserPhone(phone);
						usersettings.setUserPass(pass);
						usersettings.setToken(token);
						usersettings.setVi(vi);
						getBindStudentData(usersettings);
					}
				} catch (JSONException e) {
					MLog.logE(TAG,e);
				}
			}

			@Override
			public void onSubscribe(Disposable p1) {
			}
		};
		obs.subscribe(server);
	}

	/**
	*@author BREEZE
	*@description 获取学生信息
	*@param UserSettings
	*/
	@Override
	public void getBindStudentData(final UserSettings sets) {
		BaseView.getExec().execute(new Runnable(){
			public void run(){
				//TODO：获取学生相关信息
				String getBindStudentData=LepeiApiUti.getBindStudent(sets.getUserPhone(),sets.getToken());
				try {
					String result=AppTools.getWebContent(getBindStudentData);
					JSONObject obj=new JSONObject(result);
					int code=obj.getInt("code");
					MLog.log(TAG,"学生信息：",result);
					if(code==200){
						JSONArray ary=obj.getJSONArray("obj");
						JSONObject obj2=ary.getJSONObject(0);
						String rid=obj2.getString("rid");
						String studentId=obj2.getString("studentId");
						String studentName=obj2.getString("studentName");
						String schoolName=obj2.getString("schoolName");
						String classCode=obj2.getString("classCode");
						String grade=obj2.getString("grade");
						String className=obj2.getString("className");
						sets.setRid(rid);
						sets.setStudentId(studentId);
						sets.setStudentName(studentName);
						sets.setSchoolName(schoolName);
						sets.setClassName(className);
						sets.setGrade(grade);
						sets.setClassCode(classCode);
						view.setStudentInfo(sets);
					}
				} catch (Exception e) {
					MLog.logE(TAG,e);
					view.showAppBug(e);
				}
			}
		});
	}
	
	/**
	*@author BREEZE
	*@description 重置密码
	*@param 链接
	*/
	@Override
	public void resetPassword(final String link) {
		BaseView.getExec().execute(new Runnable(){
				@Override
				public void run() {
					Observable<String> observe=Observable.create(new ObservableOnSubscribe<String>(){
							@Override
							public void subscribe(ObservableEmitter<String> p1) throws Exception {
								try{
									String result_json=AppTools.getWebContent(link);
									p1.onNext(result_json);
								}catch(Exception e){
									//TODO：提示错误
									p1.onError(e);
								}
							}
					});
					Observer<String> obser=new Observer<String>(){

						@Override
						public void onComplete() {
						}

						@Override
						public void onError(Throwable p1) {
							view.showDialog("错误",p1.toString());
							MLog.logE(TAG,p1);
						}

						@Override
						public void onNext(String p1) {
							try {
								JSONObject obj=new JSONObject(p1);
								String result=obj.getString("msg");
								view.showDialog("提示",result);
							} catch (JSONException e) {
								MLog.logE(TAG,e);
							}
						}

						@Override
						public void onSubscribe(Disposable p1) {
						}
					};
					observe.subscribe(obser);
				}
		});
	}

	@Override
	public void onClick(View p1) {
		switch(p1.getId()){
			case R.id.resetpassword_ok:
				//TODO：重置密码
				String content=edittext.getText().toString();
				if("".equals(content)){
					edittext.setError("请输入新密码");
				}else if(content.length()<6){
					edittext.setError("密码长度不能小于六位");
				}else{
					UserSettings user_sets=UserSettings.getInstance(mContext);
					String link=LepeiApiUti.resetPassword(user_sets.getUserPhone(),user_sets.getUserPass(),content,user_sets.getToken());
					MLog.log(TAG,"修改密码链接："+link);
					resetPassword(link);
					dialog.dismiss();
				}
				break;
			case R.id.resetpassword_cancel:
				//TODO：取消
				if(dialog!=null&&dialog.isShowing()){
					dialog.dismiss();
				}
				break;
		}
	}
	
	/**
	*@author BREEZE
	*@description 展示重置密码框
	*@param 上下文
	*/
	@Override
	public void showResetPassword(Context context) {
		View resetview=LayoutInflater.from(context).inflate(R.layout.dialog_reset_password,null);
		edittext=resetview.findViewById(R.id.resetpassword_edittext);
		Button ok=resetview.findViewById(R.id.resetpassword_ok);
		TextView cancel=resetview.findViewById(R.id.resetpassword_cancel);
		ok.setOnClickListener(this);
		cancel.setOnClickListener(this);
		AppTools.setTypefaceChinese(context,ok);
		AppTools.setTypefaceEnglish(context,edittext);
		AppTools.setTypefaceChinese(context,cancel);
		dialog=new AlertDialog.Builder(context).create();
		dialog.setView(resetview);
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		dialog.show();
	}

	/**
	*@author BREEZE
	*@description 展示捐赠弹窗
	*@param 上下文
	*/
	@Override
	public void showCharity(final Context context) {
		MDialog mdialog=new MDialog(context);
		mdialog.setTitle("捐赠应用");
		mdialog.setMessage("本应用由本人个人制作，你们的支持便是我的动力。感谢捐赠！");
		mdialog.setPositiveButton("捐赠", new OnClickListener(){
				@Override
				public void onClick(View p1) {
					//TODO：跳转捐赠
					if(Alipay.hasInstalledAlipayClient(context)){
						Alipay.startAlipayClient(context,"fkx19850s0m1cmkso3w5n0d");
					}else{
						Toast.makeText(context,"未安装支付宝！",Toast.LENGTH_LONG).show();
					}
				}
		});
		mdialog.setNegativeBotton("取消",null);
		mdialog.show();
	}

	/**
	*@author BREEZE
	*@description 打开或关闭侧滑栏
	*@param 侧滑栏
	*/
	@Override
	public void openDrawerLayout(DrawerLayout mDrawerLayout) {
		if(mDrawerLayout.isDrawerOpen(Gravity.START)){
			mDrawerLayout.closeDrawer(Gravity.START);
		}else{
			mDrawerLayout.openDrawer(Gravity.START);
		}
	}
    
    public static final String TAG = "MainPresenter";
	
	private Context mContext;
	private IMainView view;
	private AlertDialog dialog;
	private EditText edittext;
    
    public MainPresenter(MainView view){
		mContext=view.getApplicationContext();
		this.view=view;
	}
	
	/****************
     *
     * 发起添加群流程。群号：像素小天气-官方群(912514928) 的 key 为： lepIXINtLxsva0DmS0JXS7ogRmEaNc0E
     * 调用 joinQQGroup(lepIXINtLxsva0DmS0JXS7ogRmEaNc0E) 即可发起手Q客户端申请加群 像素小天气-官方群(912514928)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
     ******************/
    public boolean joinQQGroup(Context context,String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D"+key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }
    
}
